package com.hr.lx.session.impll;

import com.hr.lx.session.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class HttpSessionImpl implements HttpSession {
    private Map<String, SessionBean> map = new HashMap<>();
    @Value("${service.servlet.session-time:30}")
    private Long sessionTime;

    @Override
    public void set(String token, Object obj) {
        if (map.containsKey(token)) {
            SessionBean sessionBean = map.get(token);
            sessionBean.obj = obj;
            sessionBean.time = calcTime(sessionTime * 1000 * 60);
        } else {
            SessionBean sessionBean = new SessionBean();
            sessionBean.obj = obj;
            sessionBean.time = calcTime(sessionTime * 1000 * 60);
            map.put(token, sessionBean);
        }
    }

    @Override
    public Object get(String token) {
        SessionBean sessionBean = map.get(token);
        if (sessionBean == null)
            return null;
        if (sessionBean.time > System.currentTimeMillis()) {
            sessionBean.time = calcTime(sessionTime * 1000 * 60);
            return sessionBean.obj;
        }
        map.remove(token);
        return null;
    }

    @Override
    public void remove(String token) {
        map.remove(token);
    }

    private Long calcTime(Long expireTime) {
        return System.currentTimeMillis() + expireTime;
    }

    public class SessionBean {
        private Object obj;
        private Long time;
    }
}
